package com.sky.webSocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
public class webSocketServer {

    private static Map<String,Session> sessions = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        sessions.put(sid,session);
        System.out.println(sid+" 连接成功");
    }
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid){
        System.out.println("收到客户端："+sid+"的消息"+message);
    }
    @OnClose
    public void onClose(@PathParam("sid") String sid){
        System.out.println("客户端："+sid+"断开");
        sessions.remove(sid);
    }

    public void sendMessage(String message){
        Collection<Session> values = sessions.values();
        for(Session session : values){
            if(session.isOpen()){
                session.getAsyncRemote().sendText(message);
            }
        }
    }
}
